import axios from 'axios';

const API_BASE_URL = '/api';

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

export interface MRPRequest {
  total_demand?: number;
  daily_demand?: number;
  order_qty?: number;
  reorder_point?: number;
  lead_time_days?: number;
  start_date?: string;
  initial_stock?: number;
  query?: string; // 添加查询字段以支持交互式查询
}

export interface InteractiveMRPRequest {
  query: string;
  params?: Record<string, any>;
}

export interface OrderInfo {
  序号: number;
  order_date: string;
  arrival_date: string;
  stock_after_arrival: number;
}

export interface DailyStockPlan {
  date: string;
  start_stock: number;
  events: string;
}

export interface MRPResponse {
  orders_info: OrderInfo[];
  daily_stock_plan: DailyStockPlan[];
}

export interface InteractiveMRPResponse {
  response: string;
  completed: boolean;
  result?: MRPResponse;
}

export interface StreamEvent {
  type: 'chunk' | 'result' | 'error' | 'end';
  content: any;
}

export const mrpService = {
  calculateMRP: async (params: MRPRequest): Promise<MRPResponse> => {
    try {
      const response = await apiClient.post<MRPResponse>('/calculate_mrp', params);
      return response.data;
    } catch (error) {
      console.error('Error calculating MRP:', error);
      throw error;
    }
  },

  calculateMRPInteractive: async (params: InteractiveMRPRequest): Promise<InteractiveMRPResponse> => {
    try {
      const response = await apiClient.post<InteractiveMRPResponse>('/calculate_mrp_interactive', params);
      return response.data;
    } catch (error) {
      console.error('Error calculating MRP interactively:', error);
      throw error;
    }
  },

  calculateMRPStream: async (params: MRPRequest): Promise<EventSource> => {
    // 构建查询参数
    const queryParams = new URLSearchParams();
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined) {
        queryParams.append(key, value.toString());
      }
    });
    
    // 创建并返回EventSource连接
    const url = `${API_BASE_URL}/calculate_mrp_stream?${queryParams.toString()}`;
    return new EventSource(url, {
      withCredentials: true
    });
  }
};